package fr.uniscol;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import fr.uniscol.editors.DepartementPropertyEditor;
import fr.uniscol.editors.EtablissementPropertyEditor;
import fr.uniscol.model.Departement;
import fr.uniscol.model.EtablissementModel;
import fr.uniscol.model.IUniscolUser;
import fr.uniscol.mvc.SessionExpireeException;
import fr.uniscol.service.IEtablissementService;
import fr.uniscol.service.IGeographieService;

@Controller
public class DonneesGeneralesController extends UniscolMainController {

	public static Logger log = Logger.getLogger(DonneesGeneralesController.class);
	
	@Autowired
	private IEtablissementService etablissementService;
	
	@Autowired
	private IGeographieService geoService;
	
	@InitBinder
	protected void initBinder(HttpServletRequest request, WebDataBinder binder){
		binder.registerCustomEditor(Departement.class, new DepartementPropertyEditor(geoService));
	}
	
	@RequestMapping("/etablissement")
	public ModelAndView edit(HttpSession session, Model model){
		
		EtablissementModel etablissement = etablissementService.getEtablissementById(getUtilisateur(session).getEtablissement().getId()); 
		
		model.addAttribute("departements", geoService.getAllDepartements());
		
		ModelAndView mv = new ModelAndView("etablissementForm", "etablissement", etablissement);
		
		/*if(etablissement.getCommune() != null){
			mv.addObject("communes", geoService.getCommunesByDepartement(etablissement.getCommune().getDepartement()));
		}*/
		
		return mv;
	}
	
	@RequestMapping("/etablissement.save")
	public ModelAndView save(@ModelAttribute("etablissement") EtablissementModel etablissement, BindingResult results, HttpSession session, Model model){
		 
		// Ajoute le pays
		etablissement.getAdresse().setPays(geoService.getPaysById(3));
		etablissement.setAcademie(geoService.getAcademieById(200));
		etablissement.getAdresse().setCommune(geoService.getCommuneById(10500));
		
		if(etablissementService.saveEtablissement(etablissement)){
			alertSuccess("etablissement.update.ok", "Les modifications ont été enregistrées", model);
			
		}else{
			alertError("etablissement.update.error", "Echec lors de la mise à jour des données", model);
		}
		
		return edit(session, model);
	}
}
